<template>
  <div>
    <el-dialog
      title="配置字幕"
      :visible.sync="show"
      width="80%"f
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="closeWindowContent">
      <div v-if="show">
        <el-steps align-center :active="step - 1" finish-status="success">
          <el-step title="选择终端"></el-step>
          <el-step title="配置字幕"></el-step>
          <el-step title="设置位置"></el-step>
          <el-step title="创建字幕"></el-step>
        </el-steps>
        <CommonTable
          v-if="step === 1"
          class="commonTable"
          ref="terminalTableRef"
          row-key="id"
          :is-selection="true"
          :is-show-index="true"
          :is-has-opera="false"
          :t-column-data="terminalListCol"
          :remote-api="getTerminalList"
          :query-params="searchObj"
          :is-reserve-select="true"
          @changeRow="changeRowMethods"
        >
        </CommonTable>

        <el-form
          ref="form"
          style="margin-top: 15px;"
          :model="contentForm"
          label-width="80px"
          v-if="step === 2"
        >
          <el-form-item label="字幕内容">
            <Editor
              @on-change="changeDmContent"
              @setDmControl="setDmControlMethods"
              :value="contentForm.content"
              ref="editor"
              :min-height="320"
            ></Editor>
          </el-form-item>
        </el-form>

        <div v-if="step === 3">
          <div class="dm-position-row">
            <div @click="setDmPos(1)" :class="dmPosition == 1? 'dm-position-col dm-position-col-active': 'dm-position-col'">
              左对齐
            </div>
            <div @click="setDmPos(2)" :class="dmPosition == 2? 'dm-position-col dm-position-col-active': 'dm-position-col'">
              水平居中
            </div>
            <div @click="setDmPos(3)" :class="dmPosition == 3? 'dm-position-col dm-position-col-active': 'dm-position-col'">
              右对齐
            </div>
            <div @click="setDmPos(4)" :class="dmPosition == 4? 'dm-position-col dm-position-col-active': 'dm-position-col'">
              上对齐
            </div>
            <div @click="setDmPos(5)" :class="dmPosition == 5? 'dm-position-col dm-position-col-active': 'dm-position-col'">
              垂直居中
            </div>
            <div @click="setDmPos(6)" :class="dmPosition == 6? 'dm-position-col dm-position-col-active': 'dm-position-col'">
              下对齐
            </div>
            <div class="dm-position-col">
              虚拟桌面：
              <el-input-number :controls="false" class="colInput" type="text" v-model="deskWidth" placeholder="水平像素" ></el-input-number>
              <span> x </span>
              <el-input-number :controls="false" class="colInput" type="text" v-model="deskHeight" placeholder="垂直像素" ></el-input-number>
            </div>
            <div class="dm-position-col">
              <el-button type="primary" v-if="!simulation" @click="handleSimulation">仿真</el-button>
              <el-button type="primary" v-if="simulation" @click="closeSimulation">关闭仿真</el-button>
            </div>

            <div class="dm-position-col">
              备注：仿真表示将字幕信息临时推送到终端，展示出来。
            </div>
          </div>

          <div class="dm-content-container">
            <vue-drag-resize
              :key="defaultMoveKey"
              ref="captionsBodyRef"
              class="captionsBody"
              :w="defaultWidth"
              :h="defaultHeight"
              :parentH="420"
              :x="moveX"
              :y="moveY"
              :isActive="true"
              :minh="16"
              :parentLimitation="true"
              @clicked="activedCaptions"
              @dragstop="moveStopEvent"
              @resizestop="moveStopEvent"
            >
              <div class="contentForm">
                <div v-html="contentForm.content"></div>
              </div>
              <span class="positionXY">
                ({{ moveX }},{{ moveY }})
              </span>
              <span class="positonW">W:{{ defaultWidth }}</span>
              <span class="positonH">H:{{ defaultHeight }}</span>
            </vue-drag-resize>
          </div>
        </div>

        <div v-if="step === 4">
          <el-form
            ref="form"
            style="margin-top: 15px;"
            :model="contentForm"
            label-width="80px"
          >
            <el-form-item label="字幕名称">
              <el-input type="text" v-model="contentForm.title"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeWindowContent">取 消</el-button>
          <el-button type="primary" v-if="step > 1" @click="prevStep">上一步</el-button>
        <el-button type="primary" @click="confirmSetCaptionsContent">{{step < 4?'下一步': '确认'}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VueDragResize from 'vue-drag-resize'
import Editor from "@/components/Editor/index.vue";
import {terminalListCol} from '../tableCol/terminalListCol'
import * as TerminalService from '@/views/terminal/service'
import * as Service from '../service'
import {sendCmd} from '@/views/terminalDetail/utils/sendCmd'
export default {
  components: {
    Editor,
    VueDragResize
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    step(val) {
      console.log('step ====', val)
      if(val === 3) {
        this.$nextTick(() => {
          const parentDom = document.querySelector('.dm-content-container')
          const parentRect = parentDom.getBoundingClientRect()
          this.moveX = parseInt(parentRect.width * parseFloat(this.location.x), 10) || 0
          this.moveY = parseInt(parentRect.height * parseFloat(this.location.y), 10) || 0

          this.defaultMoveKey = this.defaultMoveKey + 1
        })
      }else if(val === 1){
        //回显
        this.$nextTick(()=> {
          this.getClientList()
          this.$refs.terminalTableRef.selectedCache = this.selectTerminalList
          this.$refs.terminalTableRef.toggleRowSelectionMethods(this.selectTerminalList)
        })
      }else if(val === 2){
        // if(this.location.width && this.location.height){
        //   this.$nextTick(()=> {
        //     this.$refs.editor.dmWidth = this.location.width
        //     this.$refs.editor.dmHeight = this.location.height
        //   })
        // }

        // 编辑的状态
        console.log('editorStyle ---', this.editorStyle)
        if(this.contentForm.id) {
          this.$nextTick(() => {
            let editorDom = document.querySelector('.editor')
            const parentContainerRect = editorDom.getBoundingClientRect()
            const parentContainerWidth = parentContainerRect.width
            const parentContainerHeight = parentContainerRect.height
            this.$refs.editor.setFontSize(this.editorStyle.fontSize.indexOf('px') !== -1?this.editorStyle.fontSize.split('px')[0]: this.editorStyle.fontSize)
            let width = parentContainerWidth * this.location.width
            let height = parentContainerHeight * this.location.height
            this.$refs.editor.dmWidth = parseInt(width, 10)
            this.$refs.editor.dmHeight = parseInt(height, 10)

          })
        }
      }
    },
    show(val) {
      this.$nextTick(() => {
        if (val) {
          this.getClientList()
        }
      })
    }
  },
  data() {
    return {
      simulation: false,
      defaultMoveKey: 1,
      moveX: 0,
      moveY: 0,
      contentForm: {
        title: '',
        content: '',
        text: '',
        id: null,
      },
      defaultWidth: 120,
      defaultHeight: 20,
      dmPosition: 1,
      step: 1,
      terminalListCol,
      getTerminalList: TerminalService.getClientList,
      searchObj: {
        name: '',
        groupId: '',
        page: 1,
        pageSize: 20
      },
      editorStyle: {
        fontSize: '',
        fontFamily: '',
        color: '',
        textAlign: ''
      },
      selectTerminalList: [],
      location: {},
      deskWidth:1920,
      deskHeight:1080,
    }
  },
  methods: {
    handleSimulation() {
      this.simulation = true;
      this.getLocation();
      let object = this.location;
      // alert(JSON.stringify(this.selectTerminalList))
      this.selectTerminalList.forEach((clientDetail) => {
        const rateX = Number(clientDetail.resolution_rate.split('*')[0])
        const rateY = Number(clientDetail.resolution_rate.split('*')[1])
        let width = Math.ceil(object.width * rateX); // 计算百分比绘制窗口
        let height = Math.ceil(object.width * rateY);
        let y = Math.ceil(object.y * rateY);
        let x = Math.ceil(object.x * rateX);
        object.x = x;
        object.y = y;
        object.width = width;
        object.height = height;
        // object.color="#66FFFFFF"
        object.width = width ;  // 固定分辨率1920*1080
        object.height = height;
        object.scene = 1; //默认为1
        object.name = this.contentForm.text;

        // 发送弹幕指令
        sendCmd('captions', 'start', object);
        // if(item.open) {
        //   sendCmd('captions', 'start', object);
        // } else {
        //   sendCmd('captions', 'close', object)
        // }
      })
    },
    closeSimulation() {
      this.simulation = false;
      this.selectTerminalList.forEach((clientDetail) => {
        let object = {"scene" : 1};
        // 关闭弹幕指令
        sendCmd('captions', 'close', object);
      })
    },
    activedCaptions(row) {
      console.log('row', row)
    },
    moveStopEvent(row) {
      console.log('row ---', row)
      this.moveX = row.left
      this.moveY = row.top
      this.defaultWidth = row.width
      this.defaultHeight = row.height
    },
    toggleRows(row) {
      console.log('row ---', row)
      Object.keys(this.contentForm).forEach((keys) => {
        this.contentForm[keys] = row[keys]
      })
      if(row.location) {
        this.location = JSON.parse(row.location)
        Object.keys(this.editorStyle).forEach((key) => {
          this.editorStyle[key] = this.location[key]
        })
      }
      this.contentForm.id = row.id
      this.$nextTick(() => {
        let rowTmp = {
          id: row.client_id
        }
        this.$refs.terminalTableRef.toggleRowSelectionMethods([rowTmp], true);

      })
    },
    changeDmContent(row) {
      console.log('row', row)
      this.contentForm.content = row.html
      this.contentForm.text = row.text.replace('\n', '')
    },
    setDmControlMethods(row) {
      console.log('setDmControlMethods ---', row)
      this.defaultWidth = Number(row.width)
      this.defaultHeight = Number(row.height)
    },
    getClientList() {
      const params = Object.assign({}, this.searchObj)
      this.$refs.terminalTableRef.queryData(params)
    },
    closeWindowContent() {
      this.step = 1
      this.contentForm.content = ''
      this.contentForm.title = ''
      this.location = {}
      this.$emit('close')
    },
    changeRowMethods(rows) {
      this.selectTerminalList = [...rows]
    },
    // 1左对齐 2水平居中 3右对齐 4上对齐 5垂直居中 6下对齐
    setDmPos(pos) {
      const parentDom = document.querySelector('.dm-content-container')
      const parentRect = parentDom.getBoundingClientRect()
      const captionsBodyDom = document.querySelector('.captionsBody')
      const captionsBodyRef = this.$refs.captionsBodyRef
      const captionRect = captionsBodyRef.rect
      if(pos == 1) {
        this.moveX = 0
        this.defaultMoveKey = this.defaultMoveKey + 1
      } else if(pos == 2) {
        this.moveX = parseFloat(parentRect.width / 2) - parseFloat((captionRect.width / 2))
        this.$nextTick(() => {
          this.defaultMoveKey = this.defaultMoveKey + 1
        })
      } else if(pos == 3) {
        this.moveX = parentRect.width - captionRect.width
        this.defaultMoveKey = this.defaultMoveKey + 1
      } else if(pos == 4) {
        this.moveY = 0
        this.defaultMoveKey = this.defaultMoveKey + 1
      } else if(pos == 5) {
        this.moveY = parseFloat(parentRect.height / 2) - parseFloat((captionRect.height / 2))
        this.$nextTick(() => {
          this.defaultMoveKey = this.defaultMoveKey + 1
        })
      } else if(pos == 6) {
        this.moveY = parentRect.height - captionRect.height
      }
      this.dmPosition = pos
    },
    prevStep() {
      this.step = this.step - 1
    },
    getLocation() {
      const parentContainerDom = document.querySelector('.dm-content-container')
      const parentContainerRect = parentContainerDom.getBoundingClientRect()
      const parentContainerWidth = parentContainerRect.width
      const parentContainerHeight = parentContainerRect.height

      const moveTopPercent = (this.moveY / parentContainerHeight).toFixed(2)
      const moveLeftPercent = (this.moveX / parentContainerWidth).toFixed(2)

      const widthPercent = (this.defaultWidth / parentContainerWidth).toFixed(2)
      const heightPercent = (this.defaultHeight / parentContainerHeight).toFixed(2)

      // 选择的是否居中对齐
      let posActive = document.querySelector('.dm-position-col-active')

      console.log('this.contentForm.content ---', posActive.textContent)
      let alignDirect = posActive.textContent.trim()
      const map = {
        水平居中: {
          alignment: 'middle',
          valignment: 'top'
        },
        左对齐: {
          alignment: 'left',
          valignment: 'top'
        },
        右对齐: {
          alignment: 'right',
          valignment: 'top'
        },
        上对齐: {
          alignment: '',
          valignment: 'top'
        },
        垂直居中: {
          alignment: '',
          valignment: 'center'
        },
        下对齐: {
          alignment: '',
          valignment: 'bottom'
        }
      }

      console.log('map ---', map, alignDirect)
      let alignLocation = map[alignDirect]
      // let targetDom = document.createElement('div');
      // targetDom.innerHTML = this.contentForm.content.trim();
      // console.log('dom ---', targetDom.getComputedStyle())
      console.log('alignLocation ---', alignLocation)
      this.location = {
        x: moveTopPercent,
        y: moveLeftPercent,
        width: widthPercent,
        height: heightPercent,
        color: this.editorStyle.color,
        size: this.editorStyle.fontSize.split('px')[0],
        font: this.editorStyle.fontFamily,
        alignment: alignLocation.textAlign,
        valignment: alignLocation.valignment
      }
    },
    confirmSetCaptionsContent() {
      if(this.step === 1) {
        if(this.selectTerminalList.length === 0) {
          this.$message.error('请选择一个终端')
          return
        }
      } else if(this.step === 2) {
        if(this.contentForm.content === '') {
          this.$message.error('请输入弹幕内容')
          return
        }
        const domParent = document.querySelector('.ql-editor p')
        let styleValue = window.getComputedStyle(domParent)
        Object.keys(this.editorStyle).forEach((key) => {
          this.editorStyle[key] = styleValue[key]
        })
        console.log('editorStyle ---', this.editorStyle)
      } else if(this.step === 3) {
        this.getLocation();
      } else if(this.step === 4) {
        if(this.contentForm.title === '') {
          this.$message.error('请输入弹幕名称')
          return
        }
        const params = {
          "clientId": this.selectTerminalList[0].id,
          "content": this.contentForm.content,
          "title": this.contentForm.title,
          "type": this.dmPosition,
          "text": this.contentForm.text
        }
        const locationTmp = {
          ...this.location
        }
        if(this.contentForm.id) {
          params.id = this.contentForm.id
        }
        params.location = JSON.stringify(locationTmp)

        Service.saveCaption(params).then(() => {
          this.$message.success('保存成功')
          this.$emit('on-success')
          this.step = 1
          this.contentForm.content = ''
          this.contentForm.title = ''
          this.contentForm.id = null
        })
      }
      this.step += 1

    }
  }
}
</script>

<style scoped lang="scss">
  .commonTable{
    margin: 15px 0;
  }
  .dm-position-row{
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    .dm-position-col{
      min-width: 80px;
      cursor: pointer;
      padding: 10px 0;
      .colInput {
        width: 60px;
        ::v-deep.el-input__inner{
          padding: 0;
          height: 30px;
        }
      }
    }
    .dm-position-col-active{
      color: #409EFF;
    }
  }
  .dm-content-container{
    width: 100%;
    height: 420px;
    border: 1px solid #DCDFE6;
    margin-top: 10px;
    position: relative;
    box-sizing: content-box;
  }
  .captionsBody{
    .positionXY{
      position: absolute;
      top: -30px;
    }
    .positonW{
      position: absolute;
      top: -30px;
      right: 0;
    }
    .positonH{
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: -50px;
    }
  }
</style>

<style>
.new-window-container{
  position: absolute;
  top: 0;
  left: 0;
  z-index: 3000;
  background-color: rgba(229, 229, 229, 1);
}
.contentForm p{
  margin: 0;
}
</style>
